<template>
  <div class="context-menu-component menu-container" ref="menuRef">
    <a-menu
      mode="vertical"
      style="width: 220px; border: 1px solid #ccc"
      :selectable="false"
    >
      <a-menu-item
        v-for="(action, index) in actions"
        :key="index"
        @click="action.action(componentId)"
      >
        <span class="item-text">{{ action.text }}</span>
        <span class="item-shortcut">{{action.shortcut}}</span>
      </a-menu-item>
    </a-menu>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, onMounted, ref, onUnmounted,withDefaults ,defineEmits} from "vue";
import { clickInsideElement } from "../helper";
import { ActionItem } from "./createContextMenu";
import {
  Menu as aMenu,
  MenuItem as aMenuItem,
} from "ant-design-vue";
const props = withDefaults(
  defineProps<{
    actions: ActionItem[];
    triggerClass: string;
  }>(),
  {
    triggerClass: "edit-wrapper",
  }
);

const componentId = ref("");
const menuRef = ref<null | HTMLElement>(null);
const triggerContextMenu = (e: MouseEvent) => {
  const domElement = menuRef.value as HTMLElement;
  const wrapperElement = clickInsideElement(e, props.triggerClass);
  if (wrapperElement) {
    e.preventDefault();
    domElement.style.display = "block";
    domElement.style.top = e.pageY + "px";
    domElement.style.left = e.pageX + "px";
    const cid = wrapperElement.dataset.componentId;
    console.log("cid",cid);
    if (cid) {
      componentId.value = cid;
    }
  }
};
const handleClick = () => {
  const domElement = menuRef.value as HTMLElement;
  domElement.style.display = "none";
};
onMounted(() => {
  document.addEventListener("contextmenu", triggerContextMenu);
  document.addEventListener("click", handleClick);
});
onUnmounted(() => {
  document.removeEventListener("contextmenu", triggerContextMenu);
  document.removeEventListener("click", handleClick);
});
</script>

<style>
.menu-container {
  display: none;
  position: absolute;
  background: #fff;
  z-index: 2000;
}
.menu-container .ant-menu-item {
  display: flex;
  justify-content: space-between;
}
.menu-container .ant-menu-item:hover {
  background: #efefef;
}
.ant-menu-item .item-shortcut {
  color: #ccc;
}
</style>
